<template>
  <div class="content-container">
    <!-- 工具栏 -->
    <div ref="adminContentTools" class="content-tools-wrap hidden" style="border: 1px solid #f5f5f5">
      <div class="tools-left f-l">
        <div class="search-wrap" style="display: flex;">
          <el-input placeholder="请输入设备编号" v-model="query.deviceNo">
          </el-input>
		  <div class="search" @click="search">
			<el-button type="success" icon="el-icon-search">搜索</el-button>
		</div>
		<div class="name">设备名称：{{query.deviceName}}</div>
        </div>
      </div>
    </div>
	<!-- 提示 -->
	<div class="info" v-if="!query.deviceName.length" v-html="infoText">
		
	</div>
    <!-- 内容栏--表格 -->
    <div
		v-if="query.deviceName.length"
      class="content-table-wrap"
      v-loading="loading"
      loading-type="chrome-circle-turn"
      :style="{height:ResultHeight+'px'}"
    >
      <!-- <el-row :gutter="20">
  			<el-col :span="6">
  				<div class="chart-container">

  					<div id="chart_example" ></div>
  				</div>
  			</el-col>
      </el-row>-->

      <el-row :gutter="20" v-for="(item,index) in data">
        <el-col :span="6" v-for="(dataItem,key,index) in item.chartData">
          <div class="chart-container">
            <div :id="key+item.deviceNo"></div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

import {
  list,
  edit,
  del,
} from "@/api/equipment/equipment";

import {
	lastData
} from "@/api/data/chart";

import editDialog from '@/components/agriculture/equipment/editDialog.vue'  

import adminMixins from "@/mixins/admin"

let echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/gauge')
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')

export default {
  	name: 'role',
  	mixins:[adminMixins],
  	components:{
  		editDialog,
  	},
  	computed: {
	    ...mapGetters([
	      'name',
	      'permission',
	      'userInfo'
	    ])
  	},
  	data(){
  		return{
			infoText: '请在左上方输入框写入设备号进行查询',
  			chartHeight:'',
      		query:{
				deviceNo:'',
				deviceName: ''
      		},
      		//1新增，2修改
      		editType:1,
      		loading:false,
  			//修改模态框的显示隐藏
  			editDialogVisible:false,
  			data:null,
      		testData:[
        		{
		          	id:"334995096",
		          	number:"73F15233E6F3",
		          	online:'在线',
		          	name:"山东师范农场采集设备2",
		          	acquisitionTime:"2019-12-19 16:34:49",
		          	data:'18 ℃ | 36.4 %RH | 3767.9 ℃ | 16.3 %RH ',
        		}
      		],
  			page: {
    	  		pageSize: 10,
    	  		currentPage: 1,
    	  		total: 0
  	  		},
  	  		pageSizes:[10,20,30,40,50,100],
  	  		editForm:null
  		}
	  },
	  created () {
		  console.log(this.$route, '11111')
		  if (this.$route.query.deviceNo) {
			  this.query.deviceNo = this.$route.query.deviceNo;
		  }
		  
	  },
  	mounted() {

      	this.loadData()
      	this.setSize();
    },
  	/*mounted(){
    
    	this.setSize();
  		this.loadData(this.page)
  	},*/
  	methods:{
		search () {
			this.loadData()
		},
  		//设置图表高度
  		setChartHeight(){
  			let chartDom = document.getElementsByClassName('content-container')[0];
  			if(chartDom){
  				this.chartHeight = parseInt(chartDom.offsetWidth/4)+'px';
  			}

  			//alert(this.chartHeight)
  		},
		  //获取name的值
		  //空气温度·4.6℃ | 空气湿度·87.9%RH  | 光照度·196605Lux |
                // 土壤温度·5.8℃ | 土壤湿度·24.5%RH | 土壤电导率·252us/cm  | 信号强度·31RSSI | 版本号 1.2Version
  		getChartName(key){
			  let name = '', unit;
			  
  			if(key == 'version'){
				  name = '版本号'
				  unit = 'Version'
  			}
  			if(key == 'signalStrength'){
				  name = '信号强度'
				  unit = 'RSSI'
  			}
  			if(key == 'soilMoisture'){
				  name = '土壤湿度'
				  unit = '%RH'
  			}

  			if(key == 'airTemperature'){
				  name = '空气温度'
				  unit = '℃'
  			}
  			if(key == 'soilTemperature'){
				  name = '土壤温度'
				  unit = '℃'
  			}
  			if(key == 'airHumidity'){
				  name = '空气湿度'
				  unit = '%RH'
  			}
  			if(key == 'sunlight'){
				  name = '光照度'
				  unit = 'Lux'
  			}
  			if(key == 'soilConductivity'){
				  name = '土壤电导率'
				  unit = 'us/cm'
			  }
			if(key == 'electricity'){
				  name = '电量'
				  unit = 'kW·h'
			}
			if(key == 'waterFlow'){
				  name = '流量'
				  unit = 'm³'
			}
			if(key == 'waterSpeed'){
				  name = '流速'
				  unit = 'm³/h'
			}
			if(key == 'temperature1'){
                  name = '温度'
				  unit = '℃'
			}
			if(key == 'humidity1'){
                  name = '湿度'
				  unit = '%RH'
			}

			if(key == 'illuminance'){
                  name = '光照度'
				  unit = 'Lux'
			}

            if(key == 'carbonDioxideConcentration'){
                  name = '二氧化碳浓度'
				  unit = 'ppm'
			}

			if(key == 'rain'){
                  name = '雨'
				  unit = 'mm'
			}
			if(key == 'snow'){
                  name = '雪'
				  unit = 'mm'
			}
			if(key == 'windSpeed'){
                  name = '风速'
				  unit = 'km/h'
			}
			if(key == 'windDirection'){
                  name = '风向'
				  unit = ''
			}
			if(key == 'temperature2'){
                  name = '土壤电导率温度'
				  unit = '℃'
			}
			if(key == 'humidity2'){
                  name = '土壤电导率湿度'
				  unit = '%RH'
			}

  			return {name, unit};
  		},
  		initChart(id,key,deviceValue){
  			let this_ = this;
  			let {name, unit} = this.getChartName(key);



      		let myChart = echarts.init(document.getElementById(id));

	      	let option = {
				 
	      		tooltip: {
					formatter: '{a} : {c}%',
	    		},
	    		toolbox: {
			        feature: {
			            // restore: {},
			            // saveAsImage: {}
			        }
	    		},
	    		series: [
			        {
			            name: name,
			            type: 'gauge',
			            min:0,
			            max:name == '电量' ? 1000 : 100,
			            axisLine:{
			            	lineStyle:{
								width:15,
							}
						},
			            splitLine:{
			            	length:20
			            },
			            pointer:{
			            	length:'60%',
			            	width:4
			            },
			            detail: {
							fontSize: 18,
							formatter: [
									'{a|' + unit + '}',
									'{b|'+ deviceValue +'}'
								].join('\n'),
								rich: {
									a: {
										color: '#333',
										lineHeight: 20
									},
									b: {
										fontSize: 18,
										borderColor: '#d7d7d7',
										borderWidth: 1,
										borderRadius: 3,
										paddingLeft: 5,
										padding: 5,
										width: 60,
										top: 10,
										fontWeight: 500,
									}
								}
			            },
			            data: [{value: deviceValue, name: name}]
			        }
	    		]
	      	};

      		myChart.setOption(option);

      		myChart.getDom().style.height = this_.chartHeight;

      		myChart.resize();
			console.log('卡看')
	      	//建议加上以下这一行代码，不加的效果图如下（当浏览器窗口缩小的时候）。超过了div的界限（红色边框）
	      	window.addEventListener('resize',function() {myChart.resize()});
  		},
  		//请求table数据
  		loadData(){
				if (!this.query.deviceNo) return;
				this.loading = true;
  			lastData(this.query.deviceNo).then((res) => {
				this.loading = false;
				if (res.data.code === 200 && res.data.data.length) {
					const result = res.data.data;
					this.query.deviceNo = result[0].deviceNo;
					this.query.deviceName = result[0].name;
					this.data = this.convertData(result);
					this.setChartHeight();
					//渲染图表
					this.renderChart(this.data)
				}else {
					this.query.deviceName = '';
					this.infoText = '暂时没有该设备相关信息';
				}
				
  			})
		},
		renderChart(data){
			if(!data.length) return;
			console.log(data, '111111')
			
				for(let key in data[0].chartData){
					
					//渲染图表
					this.$nextTick(() => {
						this.initChart(key+data[0].deviceNo, key, data[0].chartData[key])
					})
					
				}
			
		},
    	convertData(data){
    		if(data.length === 0) return [];
    		let arr = [];
    		data = data.slice();
    		data.forEach((item) => {
    			item['chartData'] = this.filterDeviceData(item)
    		})

      		return data;
    	},
    	filterDeviceData(obj){
    		let temp = {};
			
    		// if(obj.dtype == 1){
    		// 	temp['airTemperature'] = obj['airTemperature'];
    		// 	temp['airHumidity'] = obj['airHumidity'];
    		// 	temp['sunlight'] = obj['sunlight'];
    		// 	temp['soilTemperature'] = obj['soilTemperature'];
    		// 	temp['soilMoisture'] = obj['soilMoisture'];
			// 	temp['soilConductivity'] = obj['soilConductivity'];
			// }
			if(obj.categoryName == 'DTU'){
				temp['electricity'] = obj['electricity'];
                temp['waterFlow'] = obj['waterFlow'];
				temp['waterSpeed'] = obj['waterSpeed'];
			}else if(obj.categoryName == '气象站'){
				temp['temperature1'] = obj['temperature1'];//温度
                temp['humidity1'] = obj['humidity1']; //湿度
				temp['illuminance'] = obj['illuminance'];//光照度
				temp['carbonDioxideConcentration'] = obj['carbonDioxideConcentration'];//二氧化碳浓度
				temp['rain'] = obj['rain'];//雨
				temp['snow'] = obj['snow'];//雪
				temp['windSpeed'] = obj['windSpeed'];//风速
				temp['temperature2'] = obj['temperature2'];//土壤电导率温度
				temp['humidity2'] = obj['humidity2'];//土壤电导率湿度
				temp['soilConductivity'] = obj['soilConductivity'];//土壤电导率
			}else{
				temp['signalStrength'] = obj['signalStrength'];
			    temp['version'] = obj['version'];
            	temp['airTemperature'] = obj['airTemperature'];
    			temp['airHumidity'] = obj['airHumidity'];
    			temp['sunlight'] = obj['sunlight'];
    			temp['soilTemperature'] = obj['soilTemperature'];
    			temp['soilMoisture'] = obj['soilMoisture'];
				temp['soilConductivity'] = obj['soilConductivity'];
			}

    		return temp;
    	},
    //新增
    handleAdd(){
        this.editForm = null;
        this.editType = 1;
        //模态框显示
        this.editDialogVisible = true;
    },
    //刷新当前页
    refresh(){
      this.loadData(this.page)
    },
  	//点击操作的编辑
  	handleEdit(row){
  		this.editType = 2;
      this.editForm = row;
      //模态框显示
      this.editDialogVisible = true;
      
  	},
  	//点击操作的删除
  	handleDel(row){
  		console.log(row)

  		this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
          	confirmButtonText: '确定',
          	cancelButtonText: '取消',
          	type: 'warning'
        }).then(()=>{
        	return del(row.id);
        }).then((res) => {

        	this.loadData(this.page)
          	this.$message({
            	type: 'success',
            	message: '删除成功!'
          	});
        }).catch(() => {
          	this.$message({
            	type: 'info',
            	message: '已取消删除'
          	});          
        });
  	},
  	//取消
  	editDialogCancel(){
  		this.editDialogVisible = false;
  		this.editForm = null;
  	},
    //确认
    editDialogConfirm(form){
      this.editDialogVisible = false;

      edit(form.data).then((res)=>{

        //this.editDialogVisible = false;
        this.loadData(this.page)
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
      })

      
    },
    //获取设备在线状态
    getDeviceStatus(data){
      if(!data) return false;
      if(data.dtype == 1){
        if(data.status == 1){
          return true
        }else{
          return false
        }
      }
      if(data.dtype == 2){
        if(data.status1 == 1 || data.status2 == 1 || data.status3 == 1 || data.status4 == 1){
          return true;
        }else{
          return false
        }
      }

      return false
    },
    //获取设备数据
    getDeviceData(row){
      var arr = [];
      //空气湿度
      if(row.airHumidity){
        arr.push("空气湿度："+row.airHumidity)
      };
      //空气温度
      if(row.airTemperature){
        arr.push("空气温度："+row.airTemperature)
      };
      //土壤电导率
      if(row.soilConductivity){
        arr.push("土壤电导率："+row.soilConductivity)
      };
      //土壤湿度
      if(row.soilMoisture){
        arr.push("土壤湿度："+row.soilMoisture)
      };
      //土壤温度
      if(row.soilTemperature){
        arr.push("土壤温度："+row.soilTemperature)
      };
      //光照
      if(row.sunlight){
        arr.push("光照："+row.sunlight)
      }


      //继电器相关
      if(String(row.status1)){
        row.status1 == 1 ? arr.push("继电器1：开") : arr.push("继电器1：关")
      }

      if(String(row.status2)){
        row.status2 == 1 ? arr.push("继电器2：开") : arr.push("继电器2：关")
      }

      if(String(row.status3)){
        row.status3 == 1 ? arr.push("继电器3：开") : arr.push("继电器3：关")
      }

      if(String(row.status4)){
        row.status4 == 1 ? arr.push("继电器4：开") : arr.push("继电器4：关")
      }

      if(arr.length){
        return arr.join('|')
      }

      return '';
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  &-container {
  }
  /***搜索栏***/
  &-search-wrap {
    padding: 15px;
    border-bottom: 1px solid #e8ebee;
  }
  /***工具栏***/
  &-tools-wrap {
    padding: 15px;
  }
  /***内容栏***/
  &-table-wrap {
    position: relative;
    padding: 15px;
    .cell {
      .icon {
        margin-right: 10px;
      }
    }
  }
  /***分页***/
  &-pagination-wrap {
    text-align: right;
    padding-top: 15px;
  }
}
.search {
	    background-color: #F5F7FA;
    color: #909399;
    vertical-align: middle;
    display: table-cell;
    position: relative;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    white-space: nowrap;
    display: flex;
    justify-content: center;
    align-items: center;
	cursor: pointer;
}
.info {
	height: 50px;
    text-align: center;
    line-height: 50px;
    font-size: 30px;
    font-weight: 500;
    margin-top: 100px;
    color: #e25252;
}
.name {
	line-height: 40px;
	width: 300px;
	margin-left: 30px;
}
</style>
